package com.lxf.net;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class SessionUtil {
	
	//获取session中的值
	public void getSession(HttpServletRequest request){
		Object a = request.getSession().getAttribute("a");
		if(a == null){
			Cookie cookie = getCookie(request, "");
			if(cookie!=null){
				//a = .a..
				//查询并设置进入cookie
				//setCookieBack();
			}
		}
	}
	
	/**
	 * 根据cookie中想取的字段获取对象
	 * @param request
	 * @param key
	 */
	private static Cookie getCookie(HttpServletRequest request, String key){
		Cookie findCookie = null;
		Cookie[] cookies = request.getCookies();
		if(cookies!=null){
			for(Cookie cookie : cookies){
				if(key.equals(cookie.getName())){
					findCookie = cookie;
					break;
				}
			}
		}
		return findCookie;
	}
	
	/**
	 * 将用户id设置为cookie并保存在客户端30天;
	 * @param userId
	 */
	public static void setCookieBack(HttpServletResponse response, Long userId, String key){
		Cookie cookie = new Cookie(key, userId.toString());
		cookie.setPath("/");//设置主路径;必须设置路径,不然其他界面访问不到;
		cookie.setMaxAge(60*60*24*30);//30天 60*60*24*30 ; 5分钟60*5
		response.addCookie(cookie);
	}

}
